package com.makingTeam.comment.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 动态线程池
 * 基于定时任务
 */
@Component
@Slf4j(topic = "api-log")
public class DynamicThread {

    //任务计数器
    private static AtomicInteger atomicInteger=new AtomicInteger(0);
    private static ThreadPoolExecutor threadPoolExecutor;
    private static final int coreNum=2;
    private static final int maxNum=4;
    private static final int idleNum=1024;
    private static final String threadName="DynamicThread";

    @PostConstruct
    public void init(){
         threadPoolExecutor=new ThreadPoolExecutor(
                 coreNum,
                 maxNum,
                 60L,
                 TimeUnit.SECONDS,
                 new LinkedBlockingDeque<>(idleNum),
                 r -> new Thread(r, threadName + "-" + atomicInteger.get()),
                 (r, executor) -> {
                     if (!executor.isShutdown()) {
                         try {
                             //尝试阻塞式加入任务队列
                             executor.getQueue().put(r);
                         } catch (Exception e) {
                             //保持线程的中断状态
                             Thread.currentThread().interrupt();
                         }
                     }
                 }
         );
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(this::adjustThreadPoolSize,1,1,TimeUnit.SECONDS);
    }


    public ThreadPoolExecutor getThreadPoolExecutor(){
        return threadPoolExecutor;
    }


    public void execute(Runnable task) {
        atomicInteger.incrementAndGet();
        threadPoolExecutor.execute(() -> {
            try {
                task.run();
            } finally {
                atomicInteger.decrementAndGet();
            }
        });
    }

    private void adjustThreadPoolSize() {
        int currentActiveTasks = atomicInteger.get();
        int currentPoolSize = threadPoolExecutor.getPoolSize();
        int corePoolSize = threadPoolExecutor.getCorePoolSize();
        int maximumPoolSize = threadPoolExecutor.getMaximumPoolSize();

        // 如果当前活跃任务数大于当前线程数且小于最大线程数，则增加线程
        if (currentActiveTasks > currentPoolSize && currentPoolSize < maximumPoolSize) {
            threadPoolExecutor.setCorePoolSize(currentPoolSize + 1);
        }
        // 如果当前活跃任务数小于当前线程数且大于核心线程数，则减少线程
        if (currentActiveTasks < currentPoolSize && currentPoolSize > corePoolSize) {
            threadPoolExecutor.setCorePoolSize(currentPoolSize - 1);
        }
    }


    @PreDestroy
    public void shutdown() {
        threadPoolExecutor.shutdown();
    }


}
